<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>终点登记</title>
    <!-- 引入WeUI CSS -->
    <link rel="stylesheet" href="./weui/weui.min.css">
    <style>
        /* 全局样式 */
        body {
             background: linear-gradient( 135deg, #348d5f 0%, #bfbf86 100%);
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            min-height: 100vh;
            padding-bottom: 20px;
              
        }
        
        .page-container {
            max-width: 600px;
            margin: 0 auto;
            padding: 15px;
        }
        
        /* 头部样式优化 */
        .header {
            text-align: center;
            margin-bottom: 25px;
            padding: 25px 0 15px;
            position: relative;
        }
        
        .header::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 60px;
            height: 4px;
           background: linear-gradient(to right, #07C160, #ffffff);
            border-radius: 2px;
        }
        
        .header-title {
            font-size: 26px;
            color: #fff;
            font-weight: 600;
            margin-bottom: 10px;
            letter-spacing: 1px;
        }
        
        /* 订单选择下拉框样式 */
        .order-select-container {
            background-color: #fff;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
        }
        
        .order-select-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 15px;
            border: 1px solid #e5e5e5;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            background-color: #f8f9fa;
        }
        
        .order-select-header:hover {
            border-color: #07C160;
            background-color: rgba(7, 193, 96, 0.05);
        }
        
        .order-select-header.active {
            border-color: #07C160;
            background-color: rgba(7, 193, 96, 0.08);
        }
        
        .order-select-title {
            font-size: 16px;
            font-weight: 600;
            color: #333;
        }
        
        .order-select-arrow {
            transition: transform 0.3s ease;
            color: #666;
            font-size: 12px;
        }
        
        .order-select-arrow.open {
            transform: rotate(180deg);
        }
        
        .selected-order-display {
            margin-top: 10px;
            padding: 12px 15px;
            background-color: #f8f8f8;
            border-radius: 6px;
            font-size: 15px;
            color: #333;
            font-weight: 500;
            text-align: center;
            border: 1px dashed #ddd;
        }
        
        .selected-order-display .order-number {
            font-weight: 600;
            color: #07C160;
        }
        
        .order-select-list {
            position: absolute;
            top: 25%;
            left: 20px;
            right: 20px;
            background-color: white;
            border: 1px solid #e5e5e5;
            border-radius: 8px;
            max-height: 300px;
            overflow-y: auto;
            z-index: 10;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            display: none;
        }
        
        .order-select-list.open {
            display: block;
        }
        
        .order-search-container {
            padding: 15px;
            border-bottom: 1px solid #f0f0f0;
            position: sticky;
            top: 0;
            background-color: white;
            z-index: 5;
        }
        
        .order-search-input {
            width: 100%;
            height: 40px;
            border: 1px solid #e5e5e5;
            border-radius: 8px;
            padding: 0 15px;
            font-size: 14px;
            box-sizing: border-box;
            transition: all 0.3s ease;
        }
        
        .order-search-input:focus {
            border-color: #07C160;
            outline: none;
            box-shadow: 0 0 0 2px rgba(7, 193, 96, 0.1);
        }
        
        .order-item {
            padding: 15px;
            border-bottom: 1px solid #f0f0f0;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .order-item:last-child {
            border-bottom: none;
        }
        
        .order-item:hover {
            background-color: rgba(7, 193, 96, 0.05);
        }
        
        .order-item.active {
            background-color: rgba(7, 193, 96, 0.1);
            border-left: 3px solid #07C160;
        }
        
        .order-item-number {
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
            font-size: 15px;
        }
        
        .order-item-meta {
            display: flex;
            gap: 15px;
            font-size: 12px;
            color: #666;
        }
        
        .order-item-company {
            flex: 1;
        }
        
        .order-loading {
            text-align: center;
            padding: 20px;
            color: #999;
            font-size: 14px;
        }
        
        .order-empty {
            text-align: center;
            padding: 30px 20px;
            color: #999;
            font-size: 14px;
        }
        
        /* 表单样式优化 */
        .weui-form {
            background-color: #fff;
            border-radius: 16px;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
            overflow: hidden;
            transition: transform 0.3s ease;
        }
        
        .weui-form:hover {
            transform: translateY(-3px);
        }
        
        .weui-cells {
            margin-top: 0;
        }
        
        .weui-cell {
            padding: 18px 0;
            transition: background-color 0.2s;
        }
        
        .weui-cell:active {
            background-color: rgba(7, 193, 96, 0.05);
        }
        
        .weui-label {
            font-size: 17px;
            color: #333;
            width: 80px;
            font-weight: 500;
        }
        
        .weui-input, .weui-select {
            font-size: 16px;
            color: #333;
            padding: 10px 0;
            transition: border-color 0.3s;
            border-bottom: 1px solid #e5e5e5;
            width: 100%;
        }
        
        .weui-input:focus, .weui-select:focus {
            border-bottom: 2px solid #07C160;
            padding-bottom: 9px;
        }
        
        .input-container {
            display: flex;
            align-items: center;
            width: 100%;
        }
        
        .weui-cell__bd {
            flex: 1;
        }
        
        /* 只读订单号样式 */
        .order-display {
            font-size: 16px;
            color: #333;
            padding: 10px 0;
            border-bottom: 1px solid #e5e5e5;
            font-weight: 500;
        }
        
        /* 重量输入组样式 */
        .weight-group {
            display: flex;
            gap: 10px;
            margin-top: 10px;
             align-items: center;
        }
        
        .weight-group .weui-input {
            flex: 1;
        }
        
        /* 图片预览容器 */
        .preview-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 10px;
        }
        
        .preview-item {
            width: calc(42.333% - 10px);
            border: 1px dashed #ccc;
            padding: 5px;
            border-radius: 4px;
            position: relative;
            background-color: #f9f9f9;
        }
        
        .preview-item img {
            width: 100%;
            height: 100px;
            object-fit: contain;
            cursor: pointer;
            transition: transform 0.3s;
        }
        
        .preview-item img:hover {
            transform: scale(1.02);
        }
        
        .preview-info {
            font-size: 12px;
            color: #666;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-top: 5px;
        }
        
        .preview-placeholder {
            color: #999;
            text-align: center;
            padding: 20px;
            border: 1px dashed #ddd;
            border-radius: 4px;
            width: 100%;
        }
        
        .remove-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            background-color: rgba(255,0,0,0.7);
            color: white;
            border: none;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            font-size: 12px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1;
        }
        
        /* 上传状态指示器 */
        .upload-status {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 12px;
        }
        
        /* 错误提示样式 */
        .weui-cells__tips {
            font-size: 14px;
            color: #f43530!important;
            margin-top: 6px;
            padding-left: 80px;
            display: none;
            animation: fadeIn 0.3s;
        }
        
        /* 提交按钮区域 */
        .weui-form__opr-area {
            margin: 35px 0 25px;
        }
        .weui-form__opr-area:last-child{
          margin-bottom: 20px!important;
          
        }
        .weui-btn_primary {
            background: linear-gradient(312deg, #47cb87 0%, #bfbf86);
            border-radius: 10px;
            height: 50px;
            font-size: 18px;
            font-weight: 500;
            box-shadow: 0 4px 10px rgba(7, 193, 96, 0.3);
            transition: all 0.3s;
        }
        
        .weui-btn_primary:not(.weui-btn_disabled):active {
            transform: translateY(2px);
            box-shadow: 0 2px 5px rgba(7, 193, 96, 0.3);
        }
        
        .weui-btn_disabled {
            background: #E6E6E6;
            color: #999;
            box-shadow: none;
        }
        
        /* 大图预览模态框 */
        .modal {
            display: none;
            position: fixed;
            z-index: 100;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.9);
            overflow: auto;
            touch-action: manipulation;
        }
        
        .modal-content {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
            padding: 20px;
        }
        
        .modal-img {
            max-width: 100%;
            max-height: 90vh;
            object-fit: contain;
            -webkit-user-select: none;
            user-select: none;
        }
        
        .close {
            position: absolute;
            top: 15px;
            right: 35px;
            color: #f1f1f1;
            font-size: 40px;
            font-weight: bold;
            cursor: pointer;
        }
        
        /* 加载状态 */
        .loading-text {
            color: #999;
            font-size: 14px;
            text-align: center;
            padding: 10px;
        }
        
        /* 动画效果 */
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            15%, 45%, 75% { transform: translateX(-5px); }
            30%, 60%, 90% { transform: translateX(5px); }
        }
        
        .shake {
            animation: shake 0.6s;
        }
        
        /* 响应式调整 */
        @media (max-width: 375px) {
            .weui-label {
                width: 70px;
            }
            
            .weui-cells__tips {
                padding-left: 70px;
            }
            
            .header-title {
                font-size: 22px;
            }
            
            .preview-item {
                width: calc(50% - 10px);
            }
            
            .close {
                right: 20px;
                font-size: 35px;
            }
        }
    </style>
</head>
<body>
    <div class="page-container">
        <div class="header">
            <h1 class="header-title">车辆终点登记🚛</h1>
        </div>
        
        <!-- 订单选择下拉框 -->
        <div class="order-select-container">
            <div class="order-select-header" id="orderSelectHeader">
                <div class="order-select-title " id="selectedOrderDisplay">选择订单</div>
                <div class="order-select-arrow">▼</div>
            </div>
            
            <!-- <div class="selected-order-display" id="selectedOrderDisplay">
                请选择订单
            </div> -->
            
            <div class="order-select-list" id="orderSelectList">
                <div class="order-search-container">
                    <input type="text" class="order-search-input" id="orderSearchInput" placeholder="输入公司名称搜索订单...">
                </div>
                
                <div class="order-list" id="orderList">
                    <div class="order-loading">加载中...</div>
                </div>
            </div>
        </div>
        
        <div class="weui-form">
            <div class="weui-cells__group weui-cells__group_form">
                <!-- 公司名称输入 -->
                <div class="weui-cells weui-cells_form">
                    <div class="weui-cell weui-cell_active">
                        <div class="weui-cell__hd">
                            <label class="weui-label">公司名称</label>
                        </div>
                        <div class="weui-cell__bd">
                            <input class="weui-input" id="company" type="text" placeholder="请输入公司名称" required>
                        </div>
                    </div>
                </div>
                <div class="weui-cells__tips" id="companyError">请输入公司名称</div>
                
                <!-- 货物重量输入 -->
                <div class="weui-cells weui-cells_form">
                    <div class="weui-cell weui-cell_active">
                        <div class="weui-cell__hd">
                            <label class="weui-label">货物重量</label>
                        </div>
                        <div class="weui-cell__bd">
                            <div class="weight-group">
                                <input class="weui-input" id="emptyWeight" type="text" placeholder="请输入重量" pattern="^\d+(\.\d{1,2})?$" required>kg
                            </div>
                        </div>
                    </div>
                </div>
                <div class="weui-cells__tips" id="weightError">请输入有效的重量值（整数或保留两位小数）</div>
                
                <!-- 货物照片上传 -->
                <div class="weui-cells weui-cells_form">
                    <div class="weui-cell weui-cell_active">
                        <div class="weui-cell__hd">
                            <label class="weui-label">货物照片</label>
                        </div>
                        <div class="weui-cell__bd">
                            <input class="weui-input" id="cargoPhotos" type="file" accept="image/*" multiple style="display: none;">
                            <button type="button" class="weui-btn weui-btn_default" id="uploadBtn">选择照片</button>
                            <div class="preview-container" id="cargoPreviews">
                                <div class="preview-placeholder">请上传货物照片</div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 移除了照片错误提示 -->
            </div>
            
            <div class="weui-form__opr-area">
                <button type="button" class="weui-btn weui-btn_primary" id="submitBtn">提交登记</button>
            </div>
        </div>
    </div>

    <!-- 大图预览模态框 -->
    <div id="imageModal" class="modal">
        <span class="close">&times;</span>
        <div class="modal-content">
            <img id="modalImage" class="modal-img">
        </div>
    </div>

    <!-- 引入WeUI JS -->
    <script src="./weui/weui.min.js"></script>
    <script src="./weui/axios.min.js"></script>
    <script src="./axios.js"></script>
    <script src="./api.js"></script>
    
    <script>
        // 获取DOM元素
        const orderSelectHeader = document.getElementById('orderSelectHeader');
        const selectedOrderDisplay = document.getElementById('selectedOrderDisplay');
        const orderSelectList = document.getElementById('orderSelectList');
        const orderSearchInput = document.getElementById('orderSearchInput');
        const orderList = document.getElementById('orderList');
        
        const companyInput = document.getElementById('company');
        const emptyWeightInput = document.getElementById('emptyWeight');
        const cargoPhotosInput = document.getElementById('cargoPhotos');
        const uploadBtn = document.getElementById('uploadBtn');
        const submitBtn = document.getElementById('submitBtn');
        const previewContainer = document.getElementById('cargoPreviews');
        
        // 在其他界面使用
        const baseURL = request.instance.defaults.baseURL;
        
        // 验证状态
        let isCompanyValid = false;
        let isWeightValid = false;
        
        // 存储当前预览的图片数据
        let currentPreviews = [];
        
        // 存储订单数据
        let allOrders = [];
        let selectedOrder = null;
        let currentOrderId = null;
        let currentOrderNum = '';
        let searchKeyword = '';
        let searchTimeout = null;
        
        // 从URL获取order_id参数
        function getOrderIdFromURL() {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get('order_id');
        }
        
        // 初始化隐藏所有错误提示
        document.querySelectorAll('.weui-cells__tips').forEach(el => el.style.display = 'none');
        
        // 切换订单选择下拉框
        function toggleOrderSelect() {
            if (orderSelectList.classList.contains('open')) {
                orderSelectList.classList.remove('open');
                orderSelectHeader.classList.remove('active');
                document.querySelector('.order-select-arrow').classList.remove('open');
                
                // 关闭时清空搜索框
                orderSearchInput.value = '';
                searchKeyword = '';
            } else {
                orderSelectList.classList.add('open');
                orderSelectHeader.classList.add('active');
                document.querySelector('.order-select-arrow').classList.add('open');
                
                // 打开时加载订单列表
                loadOrders();
                
                // 聚焦搜索框
                setTimeout(() => {
                    orderSearchInput.focus();
                }, 300);
            }
        }
        
        // 加载订单列表
      // 修改原有的loadOrders函数，不自动选择

    // 修改原有的loadOrders函数，不自动选择
    async function loadOrders() {
        orderList.innerHTML = '<div class="order-loading">加载中...</div>';
        
        try {
            const params = {
                openid: localStorage.getItem('wechat_openid'),
                status: 2
            };
            
            // 如果有搜索关键词，添加搜索条件
            if (searchKeyword.trim()) {
                params.company = searchKeyword.trim();
            }
            
            const response = await getOrders(params);
            const orders = response.data.data || response.data || response;
            
            if (!orders || orders.length === 0) {
                orderList.innerHTML = '<div class="order-empty">暂无待处理订单</div>';
                return;
            }
            
            // 保存订单数据
            allOrders = orders;
            
            // 渲染订单列表
            renderOrderList(orders);
            
        } catch (error) {
            console.error('加载订单失败:', error);
            orderList.innerHTML = '<div class="order-empty" style="color: #f44336;">加载失败，请重试</div>';
        }
    }
        
        // 渲染订单列表
        function renderOrderList(orders) {
            orderList.innerHTML = '';
            
            orders.forEach(order => {
                const orderItem = document.createElement('div');
                orderItem.className = 'order-item';
                orderItem.dataset.id = order.id;
                orderItem.dataset.orderNum = order.order_num;
                
                // 如果是当前选中的订单，添加active类
                if (selectedOrder && selectedOrder.id === order.id) {
                    orderItem.classList.add('active');
                }
                
                orderItem.innerHTML = `
                    <div class="order-item-number">${order.order_num || order.id}</div>
                    <div class="order-item-meta">
                        <span class="order-item-company">${order.company}</span>
                    </div>
                `;
                
                orderItem.addEventListener('click', function() {
                    selectOrder(order);
                });
                
                orderList.appendChild(orderItem);
            });
        }
        
        // 选择订单
         // 修改selectOrder函数，同时更新公司名称
    // 选择订单
    function selectOrder(order) {
        selectedOrder = order;
        currentOrderId = order.id;
        currentOrderNum = order.order_num || order.id;
        
        // 更新选中的订单显示
        selectedOrderDisplay.innerHTML = `<span class="order-number">${currentOrderNum}</span>`;
        
    
        
        // 关闭下拉列表
        if (orderSelectList.classList.contains('open')) {
            toggleOrderSelect();
        }
        
        // 更新订单列表中的选中状态
        updateOrderListSelection(order.id);
    }
        
        // 更新订单列表中的选中状态
        function updateOrderListSelection(selectedOrderId) {
            const orderItems = document.querySelectorAll('.order-item');
            orderItems.forEach(item => {
                if (item.dataset.id == selectedOrderId) {
                    item.classList.add('active');
                } else {
                    item.classList.remove('active');
                }
            });
        }
        
        // 搜索订单
        function searchOrders(keyword) {
            searchKeyword = keyword.trim();
            
            if (!searchKeyword) {
                // 如果没有搜索关键词，显示所有订单
                loadOrders();
                return;
            }
            
            // 防抖搜索
            if (searchTimeout) {
                clearTimeout(searchTimeout);
            }
            
            searchTimeout = setTimeout(() => {
                loadOrders();
            }, 500);
        }
        
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 如果有URL参数，直接使用该订单
            const urlOrderId = getOrderIdFromURL();
              if (urlOrderId) {
            // 根据order_id加载订单并设置选中状态
            loadOrdersAndSelectById(urlOrderId);
        } else {
            // 没有URL参数，加载订单列表并自动选择第一条
            loadOrdersAndSelectFirst();
        }
            
            // 事件监听器
            orderSelectHeader.addEventListener('click', toggleOrderSelect);
            
            orderSearchInput.addEventListener('input', function(e) {
                searchOrders(e.target.value);
            });
            
            // 阻止搜索框点击事件冒泡
            orderSearchInput.addEventListener('click', function(e) {
                e.stopPropagation();
            });
            
            // 点击页面其他区域关闭下拉列表
            document.addEventListener('click', function(event) {
                if (!orderSelectHeader.contains(event.target) && orderSelectList.classList.contains('open')) {
                    toggleOrderSelect();
                }
            });
        });
   // 新增函数：根据order_id加载并选择对应订单
    async function loadOrdersAndSelectById(orderId) {
        orderList.innerHTML = '<div class="order-loading">加载中...</div>';
        selectedOrderDisplay.innerHTML = '<div class="loading-text">加载订单信息...</div>';
        
        try {
            const params = {
                openid: localStorage.getItem('wechat_openid'),
                status: 2
            };
            
            const response = await getOrders(params);
            const orders = response.data.data || response.data || response;
            
            if (!orders || orders.length === 0) {
                orderList.innerHTML = '<div class="order-empty">暂无待处理订单</div>';
                selectedOrderDisplay.innerHTML = '请选择订单';
                return;
            }
            
            // 保存订单数据
            allOrders = orders;
            
            // 根据order_id查找对应的订单
            const targetOrder = orders.find(order => order.id == orderId || order.order_num == orderId);
            
            if (targetOrder) {
                // 找到对应订单，选择它
                selectOrder(targetOrder);
                // 渲染订单列表
                renderOrderList(orders);
            } else {
                // 没有找到对应订单，显示错误信息
                selectedOrderDisplay.innerHTML = `<span style="color: #f44336;">未找到订单: ${orderId}</span>`;
                // 渲染订单列表但不选择任何订单
                renderOrderList(orders);
            }
            
        } catch (error) {
            console.error('加载订单失败:', error);
            orderList.innerHTML = '<div class="order-empty" style="color: #f44336;">加载失败，请重试</div>';
            selectedOrderDisplay.innerHTML = `<span style="color: #f44336;">加载失败: ${orderId}</span>`;
        }
    }
        // 公司名称验证
        function validateCompany(company) {
            return company.trim().length >= 2 && company.trim().length <= 50;
        }
         // 新增函数：加载订单并自动选择第一条
   // 加载订单并自动选择第一条
    async function loadOrdersAndSelectFirst() {
        orderList.innerHTML = '<div class="order-loading">加载中...</div>';
        
        try {
            const params = {
                openid: localStorage.getItem('wechat_openid'),
                status: 2
            };
            
            const response = await getOrders(params);
            const orders = response.data.data || response.data || response;
            
            if (!orders || orders.length === 0) {
                orderList.innerHTML = '<div class="order-empty">暂无待处理订单</div>';
                selectedOrderDisplay.innerHTML = '请选择订单';
                return;
            }
            
            // 保存订单数据
            allOrders = orders;
            
            // 自动选择第一条订单
            if (orders.length > 0) {
                selectOrder(orders[0]);
            }
            
            // 渲染订单列表
            renderOrderList(orders);
            
        } catch (error) {
            console.error('加载订单失败:', error);
            orderList.innerHTML = '<div class="order-empty" style="color: #f44336;">加载失败，请重试</div>';
            selectedOrderDisplay.innerHTML = '请选择订单';
        }
    }
        // 重量验证 - 支持整数或保留两位小数
        function validateWeight(weight) {
            // 正则表达式：匹配整数或最多两位小数的数字
            const weightRegex = /^\d+(\.\d{1,2})?$/;
            
            if (!weightRegex.test(weight)) {
                return false;
            }
            
            const weightValue = parseFloat(weight);
            return !isNaN(weightValue) && weightValue > 0;
        }
        
        // 格式化重量输入
        function formatWeightInput(value) {
            // 移除非数字字符，除了小数点
            let cleaned = value.replace(/[^\d.]/g, '');
            
            // 确保只有一个小数点
            const parts = cleaned.split('.');
            if (parts.length > 2) {
                cleaned = parts[0] + '.' + parts.slice(1).join('');
            }
            
            // 限制小数点后最多两位
            if (parts.length === 2) {
                cleaned = parts[0] + '.' + parts[1].slice(0, 2);
            }
            
            return cleaned;
        }
        
        // 更新提交按钮状态
        function updateSubmitButton() {
            // submitBtn.disabled = !(isCompanyValid && isWeightValid);
        }
        
        // 公司名称输入验证
        companyInput.addEventListener('input', function() {
            const company = this.value.trim();
            isCompanyValid = validateCompany(company);
            const companyError = document.getElementById('companyError');
            
            if (company.length > 0) {
                if (isCompanyValid) {
                    companyError.style.display = 'none';
                } else {
                    companyError.style.display = 'block';
                }
            } else {
                companyError.style.display = 'none';
            }
            
            updateSubmitButton();
        });
        
        // 重量输入验证
        function validateWeightInputs() {
            const weightValue = emptyWeightInput.value.trim();
            isWeightValid = validateWeight(weightValue);
            const weightError = document.getElementById('weightError');
            
            if (weightValue.length > 0) {
                if (isWeightValid) {
                    weightError.style.display = 'none';
                } else {
                    weightError.style.display = 'block';
                }
            } else {
                weightError.style.display = 'none';
            }
            
            updateSubmitButton();
        }
        
        // 重量输入格式化
        emptyWeightInput.addEventListener('input', function() {
            // 格式化输入
            this.value = formatWeightInput(this.value);
            
            // 验证输入
            validateWeightInputs();
        });
        
        // 重量输入失去焦点时进一步格式化
        emptyWeightInput.addEventListener('blur', function() {
            const value = this.value.trim();
            if (value && validateWeight(value)) {
                const weightValue = parseFloat(value);
                // 确保显示两位小数，但如果是整数则不显示小数部分
                this.value = weightValue % 1 === 0 ? weightValue.toString() : weightValue.toFixed(2);
            }
        });
        
        // 照片上传按钮点击
        uploadBtn.addEventListener('click', function() {
            cargoPhotosInput.click();
        });
        
        // 照片上传处理 - 支持追加上传
        cargoPhotosInput.addEventListener('change', function(e) {
            const files = Array.from(e.target.files);
            
            if (files.length === 0) return;
            
            // 移除之前的占位符
            if (previewContainer.querySelector('.preview-placeholder')) {
                previewContainer.innerHTML = '';
            }
            
            // 处理每张图片
            files.forEach((file, index) => {
                if (!file.type.match('image.*')) return;
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    // 添加到当前预览数组
                    currentPreviews.push({
                        src: e.target.result,
                        name: file.name,
                        file: file, // 保存原始File对象
                        index: currentPreviews.length,
                        uploadedUrl: null // 用于存储上传后的URL
                    });
                    
                    // 更新预览显示
                    updatePreviews();
                    
                    // 移除了照片验证状态更新
                    updateSubmitButton();
                };
                reader.onerror = function() {
                    console.error('图片加载失败');
                };
                reader.readAsDataURL(file);
            });
            
            // 清空input以便再次选择相同文件
            cargoPhotosInput.value = '';
        });
        
        // 更新预览显示
        function updatePreviews() {
            previewContainer.innerHTML = '';
            
            if (currentPreviews.length === 0) {
                previewContainer.innerHTML = '<div class="preview-placeholder">请上传货物照片</div>';
                // 移除了照片验证状态更新
                updateSubmitButton();
                return;
            }
            
            currentPreviews.forEach((preview, index) => {
                const previewItem = document.createElement('div');
                previewItem.className = 'preview-item';
                previewItem.innerHTML = `
                    <button class="remove-btn" data-index="${index}">×</button>
                    <img src="${preview.src}" alt="预览">
                    <div class="preview-info">${preview.name}</div>
                `;
                previewContainer.appendChild(previewItem);
                
                // 添加点击放大事件
                previewItem.querySelector('img').onclick = function() {
                    showLargePreview(preview.src);
                };
                
                // 添加删除按钮事件
                previewItem.querySelector('.remove-btn').onclick = function() {
                    removeImage(this.dataset.index);
                };
            });
        }
        
        // 移除图片
        function removeImage(index) {
            // 从预览数组中移除
            currentPreviews.splice(index, 1);
            
            // 更新索引
            currentPreviews.forEach((preview, i) => {
                preview.index = i;
            });
            
            // 更新预览显示
            updatePreviews();
        }
        
        // 显示大图预览
        function showLargePreview(imageSrc) {
            const modal = document.getElementById('imageModal');
            const modalImg = document.getElementById('modalImage');
            
            modal.style.display = "block";
            modalImg.src = imageSrc;
            
            // 禁用滚动
            document.body.style.overflow = 'hidden';
        }
        
        // 关闭大图预览
        document.querySelector('.close').onclick = function() {
            document.getElementById('imageModal').style.display = "none";
            document.body.style.overflow = 'auto';
        };
        
        // 点击模态框背景关闭
        document.getElementById('imageModal').onclick = function(event) {
            if (event.target === this) {
                this.style.display = "none";
                document.body.style.overflow = 'auto';
            }
        };
        
        // 上传单张图片到服务器
        async function uploadSingleImage(file) {
            const formData = new FormData();
            formData.append('file', file);
            
            try {
                // 调用上传接口
                const response = await axios.post(baseURL+'/common/upload', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });
                
                if (response.data && response.data.code === 200) {
                    return response.data.data; // 返回上传后的URL
                } else {
                    throw new Error(response.data?.message || '上传失败');
                }
            } catch (error) {
                console.error('图片上传失败:', error);
                throw error;
            }
        }
        
        // 批量上传所有图片
        async function uploadAllImages() {
            const uploadedUrls = [];
            
            for (let i = 0; i < currentPreviews.length; i++) {
                const preview = currentPreviews[i];
                try {
                    const uploadedUrl = await uploadSingleImage(preview.file);
                    uploadedUrls.push(uploadedUrl.url);
                    
                    // 更新预览项的上传状态
                    preview.uploadedUrl = uploadedUrl.url;
                    
                    console.log(`图片 ${i + 1}/${currentPreviews.length} 上传成功:`, uploadedUrl);
                } catch (error) {
                    console.error(`图片 ${preview.name} 上传失败:`, error);
                    throw new Error(`图片 ${preview.name} 上传失败`);
                }
            }
            
            return uploadedUrls;
        }
        
        // 实际的提交逻辑
        async function performSubmit() {
            console.log(11112);
           const company = companyInput.value.trim();
            const emptyWeight = emptyWeightInput.value.trim();
            
            // 显示加载中
            const loading = weui.loading('提交中...');
            
            try {
                // 第一步：上传所有图片（如果有的话）
                let imageUrls = [];
                
                if (currentPreviews.length > 0) {
                    const imageUploadLoading = weui.loading('上传图片中...');
                    try {
                        imageUrls = await uploadAllImages();
                        imageUploadLoading.hide();
                    } catch (uploadError) {
                        imageUploadLoading.hide();
                        loading.hide();
                        weui.toast('图片上传失败，请重试', {
                            className: 'weui-toast_warn',
                            duration: 2000
                        });
                        return;
                    }
                }
                
                console.log(imageUrls,'imageUrls');
                
                // 第二步：准备提交数据
                const submitData = {
                    order_id: currentOrderId, // 使用从URL获取的order_id
                    company: company,
                    heavy: emptyWeight,
                    openid: localStorage.getItem('wechat_openid'),
                    images: imageUrls.join(',') // 拼接所有图片URL为逗号分隔的字符串
                };
                
             
        
                // 第三步：调用API提交数据
                const response = await endLogin(submitData);
                
                loading.hide();
                
                if (response.code === 200) {
                    // 显示成功提示
                    weui.toast('登记成功', {
                        className: 'weui-toast_success',
                        duration: 2000
                    });
                    
                    // 3秒后返回上一页
                    setTimeout(() => {
                        window.location.href='orderList.html';
                    }, 2000);
                } else {
                    throw new Error(response.message || '提交失败');
                }
                
            } catch (error) {
                loading.hide();
                console.error('提交失败:', error);
                
                weui.toast('提交失败，请重试', {
                    className: 'weui-toast_warn',
                    duration: 2000
                });
            }
        }
        
        // 显示确认对话框
        function showConfirmDialog() {
            weui.confirm('终点登记提交后不能再做修改，确定要提交吗？', {
                title: '确认提交',
                buttons: [{
                    label: '取消',
                    type: 'default',
                    onClick: function() {
                        // 用户点击取消，什么都不做
                        console.log('用户取消提交');
                    }
                }, {
                    label: '确定提交',
                    type: 'primary',
                    onClick: function() {
                        // 用户点击确定，执行实际的提交逻辑
                        console.log(45454115);
                        performSubmit();
                    }
                }]
            });
        }
        
        // 提交按钮点击事件
        submitBtn.addEventListener('click', function() {
            // 显示确认对话框
              
            // 最终验证
            const company = companyInput.value.trim();
            const emptyWeight = emptyWeightInput.value.trim();
            
            // 重置所有错误提示和抖动效果
            document.querySelectorAll('.weui-cells__tips').forEach(el => el.style.display = 'none');
            document.querySelectorAll('.shake').forEach(el => el.classList.remove('shake'));
            
            // 强制验证所有字段
            isCompanyValid = company.length > 0 && validateCompany(company);
            isWeightValid = emptyWeight.length > 0 && validateWeight(emptyWeight);
            // 移除了照片验证
            
            // 检查并显示未填写的字段错误
            let hasError = false;
            
            if (!company) {
                document.getElementById('companyError').textContent = "请输入公司名称";
                document.getElementById('companyError').style.display = 'block';
                companyInput.parentElement.parentElement.classList.add('shake');
                hasError = true;
            } else if (!isCompanyValid) {
                document.getElementById('companyError').textContent = "公司名称长度应在2-50个字符之间";
                document.getElementById('companyError').style.display = 'block';
                companyInput.parentElement.parentElement.classList.add('shake');
                hasError = true;
            }
            
            if (!emptyWeight) {
                document.getElementById('weightError').textContent = "请输入货物重量";
                document.getElementById('weightError').style.display = 'block';
                emptyWeightInput.parentElement.parentElement.classList.add('shake');
                hasError = true;
            } else if (!isWeightValid) {
                document.getElementById('weightError').textContent = "请输入有效的重量值（整数或保留两位小数）";
                document.getElementById('weightError').style.display = 'block';
                emptyWeightInput.parentElement.parentElement.classList.add('shake');
                hasError = true;
            }
            
            // 移除了照片验证
            
            // 如果有错误，显示提示并返回
            if (hasError) {
                // 移除抖动效果
                setTimeout(() => {
                    document.querySelectorAll('.shake').forEach(el => {
                        el.classList.remove('shake');
                    });
                }, 600);
                
                // 滚动到第一个错误的位置
                const firstErrorElement = document.querySelector('.weui-cells__tips[style="display: block;"]');
                if (firstErrorElement) {
                    firstErrorElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }
                
                return;
            }
            
            showConfirmDialog();
        });
        
        // 重置表单
        function resetForm() {
            companyInput.value = '';
            emptyWeightInput.value = '';
            currentPreviews = [];
            previewContainer.innerHTML = '<div class="preview-placeholder">请上传货物照片</div>';
            isCompanyValid = isWeightValid = false;
            updateSubmitButton();
            document.querySelectorAll('.weui-cells__tips').forEach(el => el.style.display = 'none');
        }
        
        // 初始化按钮状态
        updateSubmitButton();
    </script>
</body>
</html>